/**
 * 检查战马属性计算脚本
 * 验证战马在不同等级下的属性是否正确
 */

const mysql = require('mysql2/promise');

// 数据库配置
const dbConfig = {
  host: '43.143.253.188',
  user: 'nextjs',
  password: 'yEAiRE2jcxTyRBy5',
  database: 'nextjs',
  charset: 'utf8mb4'
};

// 战马属性配置（根据表格数据）
const zhanmaConfig = {
  name: "战马",
  attributes: {
    ap: {
      initial: 2750,
      maxLevels: {
        notPromoted: 2750,
        firstPromotion: 4142,
        secondPromotion: 5930,
        thirdPromotion: 8162,
      },
    },
    speed: {
      initial: 50,
      maxLevels: {
        notPromoted: 50,
        firstPromotion: 77,
        secondPromotion: 108,
        thirdPromotion: 143,
      },
    },
  },
};

// 属性计算公式
function calculateMountAttribute (initialValue, maxValue, maxLevel, currentLevel) {
  const levelRatio = Math.floor(currentLevel) / maxLevel;
  return Math.floor(initialValue + (maxValue - initialValue) * levelRatio);
}

async function checkZhanmaAttributes () {
  let connection;

  try {
    console.log('🔌 连接数据库...');
    connection = await mysql.createConnection(dbConfig);
    console.log('✅ 数据库连接成功');

    console.log('🐎 检查战马属性计算...\n');

    // 获取战马基础数据
    const [baseRows] = await connection.execute(
      'SELECT * FROM mount_base WHERE name = "战马"'
    );

    if (baseRows.length === 0) {
      console.log('❌ 未找到战马基础数据');
      return;
    }

    const baseData = baseRows[0];
    console.log('📊 战马基础数据:');
    console.log(`名称: ${baseData.name}`);
    console.log(`初始攻击: ${baseData.apIni}`);
    console.log(`初始速度: ${baseData.spIni}`);
    console.log(`最大攻击: ${baseData.ap}`);
    console.log(`最大速度: ${baseData.sp}`);

    // 获取角色坐骑中的战马数据（通过 mountBaseId 关联）
    const [mountRows] = await connection.execute(`
            SELECT cm.*, mb.name as mountName 
            FROM character_mounts cm 
            JOIN mount_base mb ON cm.mountBaseId = mb.id 
            WHERE cm.characterId = 2001 AND mb.name = "战马"
        `);

    if (mountRows.length === 0) {
      console.log('❌ 未找到角色战马数据');
      return;
    }

    const mountData = mountRows[0];
    console.log('\n📊 角色战马数据:');
    console.log(`名称: ${mountData.mountName}`);
    console.log(`等级: ${mountData.level}`);
    console.log(`转职等级: ${mountData.transLevel}`);
    console.log(`当前攻击: ${mountData.currentAp}`);
    console.log(`当前速度: ${mountData.currentSp}`);

    // 验证属性计算
    console.log('\n🔍 验证属性计算:');

    const level = mountData.level;
    const transLevel = mountData.transLevel || 0;

    // 根据转职等级确定最大等级和属性上限
    let maxLevel, maxAp, maxSpeed;

    switch (transLevel) {
      case 0: // 未转
        maxLevel = 100;
        maxAp = zhanmaConfig.attributes.ap.maxLevels.notPromoted;
        maxSpeed = zhanmaConfig.attributes.speed.maxLevels.notPromoted;
        break;
      case 1: // 一转
        maxLevel = 120;
        maxAp = zhanmaConfig.attributes.ap.maxLevels.firstPromotion;
        maxSpeed = zhanmaConfig.attributes.speed.maxLevels.firstPromotion;
        break;
      case 2: // 二转
        maxLevel = 140;
        maxAp = zhanmaConfig.attributes.ap.maxLevels.secondPromotion;
        maxSpeed = zhanmaConfig.attributes.speed.maxLevels.secondPromotion;
        break;
      case 3: // 三转
        maxLevel = 160;
        maxAp = zhanmaConfig.attributes.ap.maxLevels.thirdPromotion;
        maxSpeed = zhanmaConfig.attributes.speed.maxLevels.thirdPromotion;
        break;
      default:
        maxLevel = 100;
        maxAp = zhanmaConfig.attributes.ap.maxLevels.notPromoted;
        maxSpeed = zhanmaConfig.attributes.speed.maxLevels.notPromoted;
    }

    // 计算期望属性
    const expectedAp = calculateMountAttribute(
      zhanmaConfig.attributes.ap.initial,
      maxAp,
      maxLevel,
      level
    );

    const expectedSpeed = calculateMountAttribute(
      zhanmaConfig.attributes.speed.initial,
      maxSpeed,
      maxLevel,
      level
    );

    console.log(`转职等级: ${transLevel} (最大等级: ${maxLevel})`);
    console.log(`等级: ${level}`);
    console.log(`期望攻击: ${expectedAp}, 实际攻击: ${mountData.currentAp}`);
    console.log(`期望速度: ${expectedSpeed}, 实际速度: ${mountData.currentSp}`);

    const apMatch = expectedAp === mountData.currentAp;
    const speedMatch = expectedSpeed === mountData.currentSp;

    console.log(`攻击匹配: ${apMatch ? '✅' : '❌'}`);
    console.log(`速度匹配: ${speedMatch ? '✅' : '❌'}`);

    if (!apMatch || !speedMatch) {
      console.log('\n❌ 属性计算不正确，需要修复');
    } else {
      console.log('\n✅ 属性计算正确');
    }

    // 测试不同等级的属性计算
    console.log('\n📊 测试不同等级的属性计算:');
    console.log('等级\t期望攻击\t实际攻击\t期望速度\t实际速度\t攻击匹配\t速度匹配');
    console.log('----\t--------\t--------\t--------\t--------\t--------\t--------');

    for (let testLevel = 1; testLevel <= 100; testLevel += 20) {
      const testAp = calculateMountAttribute(
        zhanmaConfig.attributes.ap.initial,
        maxAp,
        maxLevel,
        testLevel
      );

      const testSpeed = calculateMountAttribute(
        zhanmaConfig.attributes.speed.initial,
        maxSpeed,
        maxLevel,
        testLevel
      );

      console.log(`${testLevel}\t${testAp}\t\t${mountData.currentAp}\t\t${testSpeed}\t\t${mountData.currentSp}\t\t${testAp === mountData.currentAp ? '✅' : '❌'}\t\t${testSpeed === mountData.currentSp ? '✅' : '❌'}`);
    }

  } catch (error) {
    console.error('❌ 检查失败:', error.message);
    throw error;
  } finally {
    if (connection) {
      await connection.end();
      console.log('🔌 数据库连接已关闭');
    }
  }
}

// 运行脚本
if (require.main === module) {
  checkZhanmaAttributes().catch((error) => {
    console.error('💥 脚本执行失败:', error.message);
    process.exit(1);
  });
}

module.exports = { checkZhanmaAttributes };
